import axios from 'axios'
import { message } from 'antd'

// create an axios instance
const service = axios.create({
  // baseURL: `/api`,
  baseURL: `${import.meta.env.VITE_BASE_URL}/`,
  timeout: 10000 // request timeout
})

let timer = null

service.interceptors.request.use(
  config => {
    config.headers['token'] = localStorage.getItem("token");
    if(localStorage.getItem("lang") == 'hk'){
      config.headers['lang'] = 'ft'
    }
    if(localStorage.getItem("lang") == 'en'){
      config.headers['lang'] = 'en'
    }
    if(localStorage.getItem("lang") == 'th'){
      config.headers['lang'] = 'zh'
    }
    //config.headers['lang']= localStorage.getItem("lang") || 'zh'
    return config
  },
  error => {
    message.error('bed request')
    Promise.reject(error)
  }
)
// 创建一个取消令牌源
const { CancelToken } = axios
let cancelTokenSource = CancelToken.source()

service.interceptors.response.use(
  response => {
    //
	if(response.data.code == 200){
		return response.data
	}
    if (response.data.status.errorCode == 401) {
      localStorage.removeItem('token')
      sessionStorage.removeItem('login')
      window.location.hash = '/login'
      if(localStorage.getItem('langs') == 'hk'){
        // message.error("未登录或登录已过期，请重新登录");
      }else if(localStorage.getItem('langs') == 'en'){
        // message.error("Not logged in or expired, please log in again");
      }else if(localStorage.getItem('langs') == 'th'){
        // message.error("未登录或登录已过期，请重新登录");
      }else{
        // message.error("未登录或登录已过期，请重新登录");
      }
      setTimeout(() => {
        message.destroy();
      },1500);
      return response.data
    }
    return response.data
  },
  err => {
   
    message.error(err.message)

    return Promise.reject(err)
  }
)






// 请求超时处理
const handleRequestTimeout = () => {
  if(localStorage.getItem('langs') == 'hk'){
    message.error("未登录或登录已过期，请重新登录");
  }else if(localStorage.getItem('langs') == 'en'){
    message.error("Not logged in or expired, please log in again");
  }else if(localStorage.getItem('langs') == 'th'){
    message.error("未登录或登录已过期，请重新登录");
  }else{
    message.error("未登录或登录已过期，请重新登录");
  }
  localStorage.removeItem('token')
  sessionStorage.removeItem('login')
  window.location.hash = '/login'
}

export const sendRequest = (config) => {
  // 设置请求超时定时器
  timer = setTimeout(handleRequestTimeout, service.defaults.timeout)

  return service({
    ...config,
    cancelToken: localStorage.getItem("token")  // 设置请求的取消令牌
  }).finally(() => {
    clearTimeout(timer)  // 清除超时定时器
  })
}









export default service
